package scriptEngine

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"github.com/dop251/goja"
)

func HasScriptEngine(manufacturer string, deviceType string, operateName string) bool {
	mutex.Lock()
	defer mutex.Unlock()

	vm, _ := Map.GetValue(engineMap, manufacturer, deviceType, operateName)
	return vm != nil
}

func GetScriptEngines(manufacturer string, deviceType string) []*goja.Runtime {
	mutex.Lock()
	defer mutex.Unlock()

	result := make([]*goja.Runtime, 0)
	val, err := Map.GetValue(engineMap, manufacturer, deviceType)
	if err != nil || val == nil {
		return result
	}
	list := val.(map[string]interface{})

	for _, vm := range list {
		result = append(result, vm.(*goja.Runtime))
	}
	return result
}

func GetScriptEngine(manufacturer string, deviceType string, operateName string) *goja.Runtime {
	mutex.Lock()
	defer mutex.Unlock()

	vm, _ := Map.GetValue(engineMap, manufacturer, deviceType, operateName)
	if vm != nil {
		return vm.(*goja.Runtime)
	}

	engine := goja.New()
	Map.SetValue(engineMap, manufacturer, deviceType, operateName, engine)
	return engine
}
